﻿package com.leqicheng.tenon.util;

import java.io.UnsupportedEncodingException;
import java.util.Map;

import org.apache.cordova.CordovaPlugin;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.entity.StringEntity;

import android.app.Activity;
import android.content.Context;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.leqicheng.tenon.GameLoader;
import com.leqicheng.tenon.TenonGameListView;
import com.leqicheng.tenon.login.PopWindow;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;

/**
 * @author ctmwd
 * @time 下午1:09:40
 * @date 2015年9月23日
 * @description 网络请求基础类，所有网络请求的类都需要继承此类。
 */
public class HttpRequest {
    private final Context mContext;
    private HttpEntity entity = null;
    private final String baseUrl;
    public final String REQUEST_FAILED = "10001";
    private static String DEFAULTVERSION = "1/";
    private String mApiVersion;
    private PopWindow mPopWindowContext;
    private CordovaPlugin mCordovaPlugin;
    private Activity mActivity;
    private GeneralCallBack mGeneralCallBack;
    private TenonGameListView mTenonGameListView;
    private GameLoader mGameLoader;

    public HttpRequest(Context context, PopWindow popWindow) {
        this.baseUrl = UrlConfig.getBaseUrl();
        this.mContext = context;
        mPopWindowContext = popWindow;
        this.mApiVersion = HttpRequest.DEFAULTVERSION;
    }

    public HttpRequest(Context context, CordovaPlugin cordovaPlugin) {
        this.baseUrl = UrlConfig.getBaseUrl();
        this.mContext = context;
        mCordovaPlugin = cordovaPlugin;
        this.mApiVersion = HttpRequest.DEFAULTVERSION;
    }

    public HttpRequest(Context context, Activity activity) {
        this.baseUrl = UrlConfig.getBaseUrl();
        this.mContext = context;
        mActivity = activity;
        this.mApiVersion = HttpRequest.DEFAULTVERSION;
    }

    public HttpRequest(Context context, GameLoader gameLoader) {
        this.baseUrl = UrlConfig.getBaseUrl();
        this.mContext = context;
        this.mGameLoader = gameLoader;
        this.mApiVersion = this.DEFAULTVERSION;
    }

    public HttpRequest(Context context, TenonGameListView tenonGameListView) {
        this.baseUrl = UrlConfig.getBaseUrl();
        this.mContext = context;
        this.mTenonGameListView = tenonGameListView;
        this.mApiVersion = this.DEFAULTVERSION;
    }

    public void AsyncHttpClientPostOnBack(final RequestTypeEnum requestType,
            Map params, String requestUri, String ApiVersion) {
        this.AsyncHttpClientPostOnBack(requestType, params, requestUri);
        this.mApiVersion = ApiVersion + "/";
    }

    public void AsyncHttpClientPostOnBack(final RequestTypeEnum requestType,
            Map params, String requestUri) {

        long time = System.currentTimeMillis() / 1000;

        String seed = "?seed=" + time;
        String token = "&token=" + MD5Utils.getToken(time);
        String requestDataInJson = JSON.toJSONString(params);

        AsyncHttpClient client = new AsyncHttpClient();
        client.setMaxRetriesAndTimeout(0, 5000);
        try {
            this.entity = new StringEntity(requestDataInJson, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String url = this.baseUrl + this.mApiVersion + requestUri + seed
                + token;
        client.post(this.mContext, url, this.entity, "application/json",
                new AsyncHttpResponseHandler() {

                    @Override
                    public void onSuccess(int statusCode, Header[] headers,
                            byte[] responseBody) {
                        HttpRequest.this.RequestSuccess(requestType,
                                statusCode, headers, responseBody);
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers,
                            byte[] responseBody, Throwable error) {
                        HttpRequest.this.RequestFailed(requestType, statusCode,
                                headers, null);
                    }
                });

    }

    protected void RequestSuccess(RequestTypeEnum requestType, int statusCode,
            Header[] headers, byte[] responseBody) {

        Log.i("HELLOWORLD SUCCESSED", requestType.toString());

        String responseBodyInString = null;
        try {
            responseBodyInString = new String(responseBody, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        JSONObject response = JSON.parseObject(responseBodyInString);
        int status = Integer.valueOf(response.getString("status"));
        String requestData = response.getString("values");
        if (this.mActivity != null) {
            ((GeneralCallBack) mActivity).onComplete(requestType, status,
                    requestData);
        } else if (this.mCordovaPlugin != null) {
            ((GeneralCallBack) mCordovaPlugin).onComplete(requestType, status,
                    requestData);
        } else if (this.mGameLoader != null) {
            ((GeneralCallBack) this.mGameLoader).onComplete(requestType,
                    status, requestData);
        } else if (mTenonGameListView != null) {
            ((GeneralCallBack) this.mTenonGameListView).onComplete(requestType,
                    status, requestData);
        } else {
            ((GeneralCallBack) mPopWindowContext).onComplete(requestType,
                    status, requestData);
        }

    }

    protected void RequestFailed(RequestTypeEnum requestType, int statusCode,
            Header[] headers, byte[] responseBody) {
        Log.i("HELLOWORLD FAILED", requestType.toString());

        if (!NetworkUtil.isNetAvailable()) {
            int status = RequestStatus.NETWORK_ERROR;
            if (this.mActivity != null) {
                ((GeneralCallBack) mActivity).onComplete(requestType, status,
                        null);
            } else if (this.mCordovaPlugin != null) {
                ((GeneralCallBack) mCordovaPlugin).onComplete(requestType,
                        status, null);
            } else if (this.mGameLoader != null) {
                ((GeneralCallBack) this.mGameLoader).onComplete(requestType,
                        status, null);
            } else if (mTenonGameListView != null) {
                ((GeneralCallBack) this.mTenonGameListView).onComplete(
                        requestType, status, null);
            } else {
                ((GeneralCallBack) mPopWindowContext).onComplete(requestType,
                        status, null);
            }
        } else if (statusCode == 0) {
            int status = RequestStatus.REQUEST_FAILED;
            if (this.mActivity != null) {
                ((GeneralCallBack) mActivity).onComplete(requestType, status,
                        null);
            } else if (this.mCordovaPlugin != null) {
                ((GeneralCallBack) mCordovaPlugin).onComplete(requestType,
                        status, null);
            } else if (this.mGameLoader != null) {
                ((GeneralCallBack) this.mGameLoader).onComplete(requestType,
                        status, null);
            } else if (mTenonGameListView != null) {
                ((GeneralCallBack) this.mTenonGameListView).onComplete(
                        requestType, status, null);
            } else {
                ((GeneralCallBack) mPopWindowContext).onComplete(requestType,
                        status, null);
            }
        } else {
            if (this.mActivity != null) {
                ((GeneralCallBack) mActivity).onComplete(requestType,
                        statusCode, null);
            } else if (this.mCordovaPlugin != null) {
                ((GeneralCallBack) mCordovaPlugin).onComplete(requestType,
                        statusCode, null);
            } else if (this.mGameLoader != null) {
                ((GeneralCallBack) this.mGameLoader).onComplete(requestType,
                        statusCode, null);
            } else if (mTenonGameListView != null) {
                ((GeneralCallBack) this.mTenonGameListView).onComplete(
                        requestType, statusCode, null);
            } else {
                ((GeneralCallBack) mPopWindowContext).onComplete(requestType,
                        statusCode, null);
            }
        }
    }
}
